//
//  STWelcomeVC.swift
//  Demo-04-TabBarTest
//
//  Created by 苏统世 on 16/5/13.
//  Copyright © 2016年 SuTon. All rights reserved.
//

import UIKit
import SnapKit
import AFNetworking
import SDWebImage

class STWelcomeVC: UIViewController {

    // MARK: - 懒加载
    /// 背景
    private lazy var backgroundView: UIImageView = UIImageView(image: UIImage(named: "ad_background"))
    /// 头像
    private lazy var iconView: UIImageView = {
        
        let imageView = UIImageView()
        let userIcom:UIImage = UIImage(named: "avatar_default_big")!

        self.holdImageFromSanbox(imageView,placeholdImage: userIcom)

        // 圆角
        imageView.layer.cornerRadius = userIcom.size.width*0.5
        imageView.layer.masksToBounds = true
        return imageView
    }()
    /// 消息label
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.alpha=0
        label.text = "欢迎归来"
        label.textAlignment=NSTextAlignment.Center
        label.textColor = UIColor.blackColor()
        label.font = UIFont.systemFontOfSize(15)
        label.sizeToFit()
        return label
    }()
    
    override func viewDidAppear(animated: Bool) {
        super.viewWillAppear(animated)
        springAnimal()
    }
    
    // MARK: - 动画
    private func springAnimal(){
        UIView.animateWithDuration(1.0, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            // snp_updateConstraints: 更新约束
            self.iconView.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(self.view).offset(160-UIScreen.mainScreen().bounds.height)
            })
            // 根据约束重新设置frame值
            self.view.layoutIfNeeded()
            }) { (_) -> Void in
                
                UIView.animateWithDuration(0.5, animations: { () -> Void in
                    self.messageLabel.alpha = 1
                    }, completion: { (_) -> Void in
                        // 切换到MainViewController
                        (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootVC(STTabBarVC())
                })
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        ///获取用户头像信息
        STUserAccountViewModel.shareManager.loadUserAccountInfo { () -> () in
            self.updateIcon(self.iconView,placeholdImage: UIImage(named: "avatar_default_big")!)
            STPrint(items: "access_token ==> \(STUserAccountViewModel.shareManager.userAccount?.access_token)")
        }
    }

    // MARK: - 初始化，判断内存\沙盒中是否有缓存图片，没有则使用
    
    private func holdImageFromSanbox(imageView:UIImageView,placeholdImage:UIImage){
        
        if let iconName = STUserAccountViewModel.shareManager.userAccount?.avatar_large{
            let cacheImage = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(iconName)
            if cacheImage != nil{
                STPrint(items: "内存或沙盒缓存中 ===> 有原图")
                imageView.image = cacheImage

            }else{
                STPrint(items: "内存或沙盒缓存中 ===> 没有图片")
                AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock({ (status) -> Void in
                    //STPrint(items: AFStringFromNetworkReachabilityStatus(status))
                    if AFStringFromNetworkReachabilityStatus(status) == "Reachable via WiFi"{
                        STPrint(items: "链接的是 WiFi 网络")
                        imageView.sd_setImageWithURL(NSURL(string: iconName)!, placeholderImage: placeholdImage)
                    }else{
                        STPrint(items: "++++++++++++++++")
                        imageView.image = placeholdImage
                    }
                })
            }
        }
    }
    
    private func updateIcon(imageView:UIImageView,placeholdImage:UIImage){
        if let iconName = STUserAccountViewModel.shareManager.userAccount?.avatar_large{
            // 从内存\沙盒缓存中获得原图
            let cacheImage = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(iconName)
            if (cacheImage != nil){
                iconView.image = cacheImage
            }else{
                iconView.sd_setImageWithURL(NSURL(string: iconName)!, placeholderImage: UIImage(named: "avatar_default_big"))
            }
        }
    }
    
    // MARK: - 设置UI
    private func setupUI(){
        view.addSubview(backgroundView)
        view.addSubview(iconView)
        view.addSubview(messageLabel)
        
        backgroundView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        iconView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.view)
            make.bottom.equalTo(self.view).offset(-160.0)
            make.size.equalTo(CGSize(width: 85, height: 85))
        }
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.view)
            make.top.equalTo(iconView.snp_bottom).offset(15.0)
        }
    }
}
